﻿using System;
using ProjectAutumn.Window;
using Tao.Sdl;

namespace ProjectAutumn.WindowSystem.SDL
{
    class SDLWindowDevice : WindowDevice
    {
        private IntPtr mainSurface;
        private unsafe Sdl.SDL_Surface* surface;
        public SDLWindowDevice(Game game)
                : base(game)
        {
        }
        public override IntPtr Handle
        {
            get { return mainSurface; }
        }
        protected override unsafe void ApplyChanges(int width, int height, bool fullscreen)
        {
            int flags = Sdl.SDL_DOUBLEBUF | Sdl.SDL_SRCALPHA;
            if (fullscreen)
                flags |= Sdl.SDL_FULLSCREEN;
            if (Game.GraphicsSystem == GraphicsSystems.OpenGL)
                flags |= Sdl.SDL_OPENGL;
            else flags |= Sdl.SDL_HWACCEL;
            mainSurface = Sdl.SDL_SetVideoMode(width, height, 32, flags);
            surface = (Sdl.SDL_Surface*)mainSurface.ToPointer();
        }
        public override void Dispose()
        {
            Sdl.SDL_FreeSurface(mainSurface);
            Sdl.SDL_Quit();
        }
        public override unsafe int Width
        {
            get { return surface->w; }
        }
        public override unsafe int Height
        {
            get { return surface->h; }
        }
        public override void SetTitle(string value)
        {
            Sdl.SDL_WM_SetCaption(value, null);
        }
        public override void Run()
        {
            Sdl.SDL_Init(Sdl.SDL_INIT_VIDEO);
            Sdl.SDL_Event evt;
            while (Sdl.SDL_PollEvent(out evt) >= 0)
            {
                Game.Tick();
                if(evt.type ==
                   Sdl.SDL_QUIT)
                    break;
            }
        }
        public override void GlFlip()
        {
            Sdl.SDL_GL_SwapBuffers();
        }
        public override WindowCapabilities WindowCapabilities
        {
            get { return new WindowCapabilities
            {
                    SupportsChangeTitle = true,
                    SupportsGLFlip = true,
            }; }
        }
    }
}
